﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;
using System.Text.RegularExpressions;
using PServiceBus.Core.Runtime.Serializers;

namespace PServiceBus.Core.Runtime.Extensions {
    public static class JsonExtension {
        private static readonly Regex _jsonDateRegex = new Regex(@"^(\d{4})(?:-?W(\d+)(?:-?(\d+)D?)?|(?:-(\d+))?-(\d+))(?:[T ](\d+):(\d+)(?::(\d+)(?:\.(\d+))?)?)?(?:Z(-?\d*))?$", RegexOptions.Compiled | RegexOptions.IgnoreCase);


        public static bool IsJsonDate(this string obj) {
            return _jsonDateRegex.IsMatch(obj);
        }

        /// <summary>
        /// Convert object to json string
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToJson(this object obj) {
            return SimpleJson.SerializeObject(obj);
        }
        /// <summary>
        /// Convert json string into generic object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static object FromJson(this string obj) {
            return SimpleJson.DeserializeObject(obj);
        }
        /// <summary>
        /// Convert json string to the specific generic type
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static T FromJson<T>(this string obj) {
            return SimpleJson.DeserializeObject<T>(obj);
        }
        /// <summary>
        /// Convert json string to the specific type
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static T FromJson<T>(this string obj, Type type) {
            return (T)SimpleJson.DeserializeObject(obj, type);
        }

        public static object ObjectToJson(this object obj) {
            if (obj == null) return null;
            var objString = obj.ToString();
            if (_jsonDateRegex.IsMatch(objString)) {
                if (!objString.StartsWith("\"", StringComparison.OrdinalIgnoreCase))
                    objString = String.Concat("\"", objString, "\"");
                return objString.FromJson<DateTime>();
            }
            return obj;
        }
    }
}
